package com.example.wm.SanWar.controller;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.SimpleColumnWidthStyleStrategy;
import com.example.wm.SanWar.entity.ExcelDetailsData;
import com.example.wm.SanWar.entity.ExcelIndexData;
import com.example.wm.common.Result;
import com.example.wm.common.ResultData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@RestController
@RequestMapping("/excel")
public class ExcelController {

    private static final Logger logger = LoggerFactory.getLogger(ExcelController.class);

    /**
     * 接收前端的 List<ExcelIndexData> 数据，生成 Excel 文件并返回
     *
     * @param excelIndexDataList 前端传递的 Excel 数据列表
     * @return 生成的 Excel 文件的字节数组
     */
    @PostMapping("/generate")
    public Result generateExcel(@RequestBody List<ExcelIndexData> excelIndexDataList) throws IOException {
        logger.debug("Received ExcelIndexDataList with size: {}", excelIndexDataList.size());

        if (excelIndexDataList == null || excelIndexDataList.isEmpty()) {
            logger.error("ExcelIndexDataList is null or empty");
            return ResultData.success(HttpStatus.BAD_REQUEST);
        }

        boolean hasContent = false;

        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
             ExcelWriter excelWriter = EasyExcel
                     .write(outputStream)
                     .registerWriteHandler(new SimpleColumnWidthStyleStrategy(20))

                     .build()) {

            // 遍历每个分组
            for (int i = 0; i < excelIndexDataList.size(); i++) {
                ExcelIndexData excelIndexData = excelIndexDataList.get(i);
                String groupName = excelIndexData.get分组(); // 使用getter方法获取分组名
                List<ExcelDetailsData> details = excelIndexData.getDetail(); // 使用getter方法获取详细数据

                logger.debug("Processing group {}: {}", i + 1, groupName);
                if (groupName == null || groupName.isEmpty()) {
                    logger.error("Group name is null or empty for item {}", i + 1);
                    continue;
                }

                // 创建sheet
                WriteSheet writeSheet = EasyExcel.writerSheet(groupName).head(createExcelHead()).build();

                // 写入表头
                logger.debug("Writing head to sheet: {}", groupName);
                excelWriter.write(new ArrayList<>(), writeSheet)
                ; // 写入空数据以确保表头被创建

                // 写入详细数据
                if (details != null && !details.isEmpty()) {
                    logger.debug("Writing {} details to sheet: {}", details.size(), groupName);
                    excelWriter.write(details, writeSheet);
                    hasContent = true;
                } else {
                    logger.warn("No details found for group: {}", groupName);
                }

                // 写入缺勤人员行
//                String absentMembers = excelIndexData.get缺勤成员(); // 使用getter方法获取缺勤人员
//                System.out.println("absentMembers:"+absentMembers);
//                if (absentMembers != null && !absentMembers.isEmpty()) {
//                    ExcelDetailsData absentRow = new ExcelDetailsData();
//
//                    absentRow.set成员("缺勤人员"); // 使用setter方法设置成员
//                    absentRow.set势力值差值(absentMembers); // 假设缺勤人员信息放在势力差值列
//                    absentRow.set战功差值(""); // 战功差值列留空
//                    absentRow.set状态("缺勤"); // 状态设置为“缺勤”
//                    logger.debug("Writing absent row to sheet: {}", groupName);
//                    excelWriter.write(Collections.singletonList(absentRow), writeSheet);
//                    hasContent = true;
//                } else {
//                    logger.warn("No absent members found for group: {}", groupName);
//                }
            }

            // 完成写入
            excelWriter.finish(); // 确保所有数据都被写入到 outputStream 中
            logger.debug("Finished writing to Excel file");

            if (!hasContent) {
                logger.error("No content found in any group");
                return ResultData.success(HttpStatus.BAD_REQUEST);
            }

            byte[] bytes = outputStream.toByteArray();
            logger.debug("Generated bytes length: {}", bytes.length);
            if (bytes.length == 0) {
                logger.error("Generated Excel file is empty");
            }

            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=excelData.xlsx");
            return ResultData.success(bytes);

        }
    }

    /**
     * 创建并返回 Excel 表头
     *
     * @return 表头数据
     */
    private List<List<String>> createExcelHead() {
        List<List<String>> head = new ArrayList<>();
        head.add(Collections.singletonList("成员"));
        head.add(Collections.singletonList("势力差值"));
        head.add(Collections.singletonList("战功差值"));
        head.add(Collections.singletonList("状态")); // 添加状态列头
        logger.debug("Created head: {}", head);
        return head;
    }
}